package com.project.personal_blog.garbage_classification_management_system.Controller;

import com.project.personal_blog.garbage_classification_management_system.pojo.Code;
import com.project.personal_blog.garbage_classification_management_system.pojo.Result;
import com.project.personal_blog.garbage_classification_management_system.pojo.User;
import com.project.personal_blog.garbage_classification_management_system.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/user")
@RestController
public class LoginController {
    @Autowired
    private LoginService loginService;

    @PostMapping("/login")
    public ResponseEntity<Result> login(@RequestBody User user) {
        // 创建一个Result对象
        Result result;
        // 判断密码长度是否在8到16位之间
        if (user.getPassword().length() < 8 || user.getPassword().length() > 16) {
            // 如果不符合，创建一个Result对象，返回400
            result = new Result("fail", Code.PASSWORD_LENGTH_ERROR, "密码长度必须在8到16位之间");
            return ResponseEntity.badRequest().body(result);
        }
        // 判断密码格式是否正确
        if (!user.getPassword().matches("^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[!@#$%^&*]).{8,16}$")) {
            // 如果不符合，创建一个Result对象，返回400
            result = new Result("fail", Code.PASSWORD_FORMAT_ERROR, "密码必须包含字母、数字和符号");
            return ResponseEntity.badRequest().body(result);
        }
        // 验证用户名和密码
        Result loginUser = loginService.login(user.getUsername(), user.getPassword());
        if (loginUser != null) {
            // 如果验证成功，创建一个Result对象，返回200
            result = new Result("success", Code.LOGIN_SUCCESS, loginUser);
        } else {
            // 如果验证失败，创建一个Result对象，返回400
            result = new Result("fail", Code.LOGIN_FAIL, "用户名或密码错误");
        }
        // 返回结果
        return ResponseEntity.ok(result);
    }
}
